'use strict';
// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});
var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 将已发货订单自动确认收货
 */
module.exports = async (event, context) => {
	let res = { code: 0, msg: "" };
	let time = Date.now();
	let dbName = "vk-mall-order";
	let timeline = { time, msg: "系统确认收货", type: "confirmReceipt", oper_type: "system", oper_uid: "system" };
	let mchInfo = await vk.baseDao.findById({
		dbName: "vk-mall-mch",
		id: "001"
	});
	let day = vk.pubfn.getData(mchInfo, "order.auto_complete", 7);
	let auto_complete_time = time + 1000 * 3600 * 24 * day; // X天后自动完成
	res.num = await vk.baseDao.update({
		dbName,
		whereJson: {
			order_type: 0, // 只有电商订单才需要确认收货
			status: 4,
			auto_confirm_receive_time: _.lte(time)
		},
		dataJson: {
			status: 5,
			confirm_receive_time: time,
			auto_complete_time,
			timeline: _.push(timeline)
		}
	});
	console.log(`成功将【${res.num}】个订单设置为【已确认收货】`)

	return res;
};
